package online.longzipeng.householdbillssystem.config;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.security.Keys;
import lombok.Data;
import online.longzipeng.householdbillssystem.business.dto.UserLoginResponseDTO;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import javax.crypto.SecretKey;
import java.util.Date;

/**
 * @uthor: lzp
 * @Date: 2021/2/7 15:43
 * 配置将对象生成加密的JSON字符串
 */
@Component
@Data
@ConfigurationProperties(prefix = "config.jwt")
public class JWTConfig {

    private String secret;
    private long expire;

    /**
     *  把指定的 UserDTO 对象 生成 token[jwt]
     */
    public String generateJwt(UserLoginResponseDTO member){

        // 加密
        byte[] keyBytes = secret.getBytes();
        // 获得密钥对象
        SecretKey key = Keys.hmacShaKeyFor(keyBytes);

        String token = Jwts.builder()
                .setHeaderParam("typ", "JWT") //令牌类型
                //.setHeaderParam("alg", "HS256") //签名算法
                .setIssuedAt(new Date()) //签发时间
                .setExpiration(new Date(System.currentTimeMillis() + expire*1000)) //过期时间
                .claim("id", member.getId())
                .claim("nick", member.getNick())
                .claim("age", member.getAge())
                .claim("userName",member.getUserName())
                .claim("avatar",member.getAvatar())
                .signWith(key, SignatureAlgorithm.HS256).compact();
        return token;
    }

    /**
     * 解析jwt
     * @param jwtToken
     * @return
     */
    public UserLoginResponseDTO checkJwt(String jwtToken){

        Jws<Claims> claimsJws = Jwts.parser().setSigningKey(this.secret.getBytes()).parseClaimsJws(jwtToken);
        // map
        Claims claims = claimsJws.getBody();
        Integer id = claims.get("id",Integer.class);
        String nick = claims.get("nick",String.class);
        Byte age = claims.get("age",Byte.class);
        String userName = claims.get("userName",String.class);
        String avatar = claims.get("avatar",String.class);


        return UserLoginResponseDTO.builder()
                .id(id)
                .userName(userName)
                .nick(nick)
                .age(age)
                .avatar(avatar)
                .build();
    }

}
